package com.lishem.top100._07linkedlist;

import com.lishem.common.ListNode;

/**
 * https://leetcode.cn/problems/reverse-nodes-in-k-group/description/
 * <p>
 * 给你链表的头节点 head ，每 k 个节点一组进行翻转，请你返回修改后的链表。
 * <p>
 * k 是一个正整数，它的值小于或等于链表的长度。
 * <p>
 * 如果节点总数不是 k 的整数倍，那么请将最后剩余的节点保持原有顺序。
 * <p>
 * 你不能只是单纯的改变节点内部的值，而是需要实际进行节点交换。
 * <p>
 * 示例 1：
 * <p>
 * 输入：head = [1,2,3,4,5], k = 2
 * <p>
 * 输出：[2,1,4,3,5]
 * <p>
 * 示例 2：
 * <p>
 * 输入：head = [1,2,3,4,5], k = 3
 * <p>
 * 输出：[3,2,1,4,5]
 */
public class _10LetCode25_K个一组翻转链表 {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode tempHead = new ListNode();
        tempHead.next = head;
        ListNode lastTail = tempHead;
        while (true) {
            ListNode cur = lastTail;
            for (int i = 0; i < k; i++) {
                if (cur != null) {
                    cur = cur.next;
                } else {
                    return tempHead.next;
                }
            }
            if (cur == null){
                return tempHead.next;
            }
            // 反转
            ListNode nextHead = cur.next;
            ListNode pre = nextHead;
            cur = lastTail.next;
            ListNode nowTile = cur;
            while (cur != nextHead) {
                ListNode next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            lastTail.next = pre;
            lastTail = nowTile;
        }
    }

    public static void main(String[] args) {
        _10LetCode25_K个一组翻转链表 sol = new _10LetCode25_K个一组翻转链表();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode.printListNode(sol.reverseKGroup(head, 2));

        System.out.println("-----------------------");
        head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode.printListNode(sol.reverseKGroup(head, 3));
    }
}
